package com.tian.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tian.mapper.DoctorsMapper;
import com.tian.mapper.HospitalMapper;

import com.tian.pojo.Hospital;
import com.tian.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.util.StringUtils;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService{
    @Autowired
    private HospitalMapper hospitalMapper;
    @Override
    public PageResult getList(PageResult pageResult) {
        IPage<Hospital> page = new Page(pageResult.getPageNum(),pageResult.getPageSize());
        QueryWrapper<Hospital> queryWrapper = new QueryWrapper<>();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag, "name", pageResult.getQuery());
        page = hospitalMapper.selectPage(page, queryWrapper);
        long total = page.getTotal();
        List<Hospital> records = page.getRecords();
        return pageResult.setTotal(total).setRows(records);
    }

    @Override
    public void deleteById(Integer id) {
        hospitalMapper.deleteById(id);
    }


    public Map<Integer,List<Hospital>> getHospitalMap(){
        Map<Integer,List<Hospital>> map = new HashMap<>();
        List<Hospital> hospitalsList = hospitalMapper.selectList(null);
        for (Hospital hospital : hospitalsList) {
            if(map.containsKey(hospital.getParentId())){
                map.get(hospital.getParentId()).add(hospital);
            }else {
                List<Hospital> hosList = new ArrayList<>();
                hosList.add(hospital);
                map.put(hospital.getParentId(), hosList);
            }
        }
        return map;
    }

    @Override
    public List<Hospital> findItemCatList(Integer type) {
        Map<Integer, List<Hospital>> map = getHospitalMap();
        List<Hospital> catList = new ArrayList<>();

        if(type == 1){//获取一级目录
            return map.get(0);
        }
        List<Hospital> hospitals = map.get(0);
        for (Hospital itemHospital : hospitals) {
            List<Hospital> list = map.get(itemHospital.getId());
            itemHospital.setChildren(list);
        }
        return hospitals;

    }
}
